﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProgNetComponentsDx.Options;
using ProgNetComponentsDx.Enums;
using Microsoft.Win32;

namespace Wydatki.Setup
{
    public partial class FormOpcje : XtraForm, IDataForm
    {
        public FormOpcje()
        {
            InitializeComponent();
            xtraTabControl1.SetTabMinSize(120);
            radioGroup1_SelectedIndexChanged(opOtwieranieFormy, EventArgs.Empty);
        }

        private string ValidationMessage;

        protected virtual bool Save()
        {
            optionProvider1.UnLockAllObjects();
            optionProvider1.CommitAllOptions();
            optionProvider1.LockAllObjects();

            RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl);

            bool result = OptionCache.SaveOptions();
            if (result && key != null)
            {
                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Uruchamianie.Autostart))
                {
                    key.SetValue("Wydatki", Application.ExecutablePath.AddDoubleQuotes());
                }
                else
                {
                    key.DeleteValue("Wydatki", false);
                }
            }
            return result;
        }
        protected virtual void FinishEdit()
        {
            if (this.ActiveControl != null && this.ActiveControl is BaseEdit)
                (this.ActiveControl as BaseEdit).SendKey(new KeyEventArgs(Keys.Enter));
            this.SelectNextControl(this.ActiveControl, true, true, true, true);
        }
        protected virtual void SaveClick()
        {
            if (ValidateAll())
            {
                if (Save())
                {
                    modeProvider1.CurrentMode = FormMode.Read;
                    changeDetectorProvider1.ResetAll();
                }
                else
                {
                    this.ShowDxErrorDialog("Błąd zapisu!");
                }
            }
            else
            {
                if (ValidationMessage.IsNull())
                    ValidationMessage = "Błąd validacji.";

                this.ShowDxErrorDialog(ValidationMessage);
            }
        }

        protected virtual void EditClick()
        {

            if (modeProvider1.CurrentMode == FormMode.Read)
            {
                modeProvider1.CurrentMode = FormMode.Edit;
            }
            else
            {
                if (changeDetectorProvider1.HasChanges)
                {
                    DialogResult res = this.ShowDxYNCQuestionDialog("Zapisać zmiany?");
                    if (res == System.Windows.Forms.DialogResult.No)
                    {
                        optionProvider1.RefreshAllOptions();
                        changeDetectorProvider1.ResetAll();
                        modeProvider1.CurrentMode = FormMode.Read;
                    }
                    else if (res == System.Windows.Forms.DialogResult.Yes)
                    {
                        SaveClick();
                    }
                }
                else
                {
                    modeProvider1.CurrentMode = FormMode.Read;
                }
            }
        }

        protected virtual void RefreshClick()
        {
            optionProvider1.RefreshAllOptions();
            changeDetectorProvider1.ResetAll();
        }
        protected virtual bool ValidateAll()
        {
            bool result = false;
            ValidationMessage = "";
            result = modeProvider1.ValidateRequiredEdits(ref ValidationMessage);
            return result;
        }

        private void bbiZapisz_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FinishEdit();
            SaveClick();
        }

        private void bbiEdytuj_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FinishEdit();
            EditClick();
        }
        
        private void bbiRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshClick();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            optionProvider1.LockAllObjects();
            modeProvider1.CurrentMode = FormMode.Edit;
        }
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            optionProvider1.UnLockAllObjects();
        }

        private void colorEdit2_Properties_KeyDown(object sender, KeyEventArgs e)
        {
            BaseEdit edit = sender as BaseEdit;
            if (!edit.Properties.ReadOnly)
            {
                if (e.KeyCode == Keys.Delete)
                {
                    edit.EditValue = null;
                }
            }
        }

        private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (opOtwieranieFormy.EditValue.AsString() == "W")
            {
                modeProvider1.GetSettings(opWybraneFormy).ReadOnlyModes = FormMode.Read | FormMode.View;
            }
            else
            {
                modeProvider1.GetSettings(opWybraneFormy).ReadOnlyModes = FormMode.All;
            }
        }

        private void changeDetectorProvider1_ContextChanged(object sender, EventArgs e)
        {
            if (changeDetectorProvider1.HasChanges)
            {
                if (!this.Text.EndsWith("*"))
                    this.Text += " *";
            }
            else
            {
                if (this.Text.EndsWith("*"))
                    this.Text = this.Text.Replace(" *", "");
            }
            modeProvider1.RefreshObject(bbiZapisz);
        }

        private void modeProvider1_CustomGetModes(object sender, ProgNetComponentsDx.Mode.CustomModeSettingsEventArgs e)
        {
            if (sender == bbiZapisz)
            {
                if (!changeDetectorProvider1.HasChanges)
                    e.IsReadOnly = true;
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (!Program.IsExit)
            {
                FinishEdit();
                if (changeDetectorProvider1.HasChanges)
                {
                    DialogResult dlg = this.ShowDxYNCQuestionDialog("Chcesz zapisać zmiany?");
                    switch (dlg)
                    {
                        case DialogResult.Cancel:
                            e.Cancel = true;
                            break;
                        case DialogResult.No:
                            break;
                        case DialogResult.Yes:
                            if (ValidateAll())
                            {
                                if (!Save())
                                {
                                    this.ShowDxErrorDialog("Błąd zapisu!");
                                    e.Cancel = true;
                                }
                            }
                            else
                            {
                                this.ShowDxWarningDialog("Błąd validacji.");
                                e.Cancel = true;
                            }
                            break;
                    }
                }
            }
            base.OnFormClosing(e);
        }

        #region IDataForm Members

        string IDataForm.Text
        {
            get
            {
                return this.Text;
            }
        }

        bool IDataForm.HasChanges
        {
            get { return this.changeDetectorProvider1.HasChanges; }
        }

        bool IDataForm.Save()
        {
            bool res = Save();
            if (res)
            {
                changeDetectorProvider1.ResetAll();
                modeProvider1.CurrentMode = ProgNetComponentsDx.Enums.FormMode.Read;
            }
            return res;
        }

        void IDataForm.FinishEdit()
        {
            this.FinishEdit();
        }

        bool IDataForm.ValidateAll()
        {
            return ValidateAll();
        }

        #endregion
    }
}
